package com.fary.chapter02_safe_thread;

/**
 * 线程安全：
 * 1.可以在方法上加synchronized
 * 2.加同步代码块，加上锁对象
 */
public class SafeThread01 implements Runnable {

    private static Integer count = 100;

    @Override
    public void run() {
        while (count > 1) {
            cal();
        }
    }

    private void cal() {
        synchronized (this) {
            try {
                Thread.sleep(20);
            } catch (Exception e) {
                e.printStackTrace();
            }
            count--;
            System.out.println(Thread.currentThread().getName() + "," + count);
        }
    }

    private synchronized void cal1() {
        try {
            Thread.sleep(20);
        } catch (Exception e) {
            e.printStackTrace();
        }
        count--;
        System.out.println(Thread.currentThread().getName() + "," + count);
    }

    private static void cal2() {
        synchronized (SafeThread01.class) {
            try {
                Thread.sleep(20);
            } catch (Exception e) {
                e.printStackTrace();
            }
            count--;
            System.out.println(Thread.currentThread().getName() + "," + count);
        }
    }


    public static void main(String[] args) {
        SafeThread01 safeThread01 = new SafeThread01();
        Thread thread1 = new Thread(safeThread01);
        Thread thread2 = new Thread(safeThread01);
        thread1.start();
        thread2.start();
    }
}
